package jnpf.message.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import jnpf.base.UserInfo;
import jnpf.base.entity.MessageTemplateEntity;
import jnpf.base.entity.SmsTemplateEntity;
import jnpf.base.entity.SysConfigEntity;
import jnpf.base.model.systemconfig.SmsModel;
import jnpf.base.service.MessageTemplateService;
import jnpf.base.service.SmsTemplateService;
import jnpf.base.service.SysconfigService;
import jnpf.base.util.SmsUtil;
import jnpf.constant.MsgCode;
import jnpf.message.entity.*;
import jnpf.message.enums.MessageTypeEnum;
import jnpf.message.model.message.DingTalkModel;
import jnpf.message.model.message.EmailModel;
import jnpf.message.model.message.SentMessageForm;
import jnpf.message.model.messagetemplateconfig.TemplateParamModel;
import jnpf.message.model.sendmessageconfig.SendConfigTemplateModel;
import jnpf.message.service.*;
import jnpf.model.BaseSystemInfo;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.UserService;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Pattern;

@Component
@Slf4j
public class TestSendConfigUtil {

    @Autowired
    private UserService userService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private SysconfigService sysconfigService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private MessagereceiveService messagereceiveService;
    @Autowired
    private SynThirdInfoService synThirdInfoService;

    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private SmsTemplateService smsTemplateService;
    @Autowired
    private MessageTemplateConfigService messageTemplateConfigService;

    @Autowired
    private TemplateParamService templateParamService;
    @Autowired
    private SmsFieldService smsFieldService;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private MessageMonitorService messageMonitorService;

    /**
     * 测试发送配置
     *
     *
     */
    public String sendMessage(SendConfigTemplateModel model,UserInfo userInfo) {
            List<String> toUserIdsList = model.getToUser();
            // 模板id
            String templateId = model.getTemplateId();
            // 参数
            Map<String, Object> parameterMap = new HashMap<>();
            List<TemplateParamModel> paramModelList = JsonUtil.getJsonToList(model.getParamJson(),TemplateParamModel.class);
            if(paramModelList != null && paramModelList.size()>0) {
                for (TemplateParamModel paramModel : paramModelList) {
                    parameterMap.put(paramModel.getField(), paramModel.getValue());
                }
            }
            boolean flag = true;
            if(!"webhook".equals(model.getMessageType())) {
                if (!(toUserIdsList != null && toUserIdsList.size() > 0)) {
                    log.error("接收人员为空");
                    flag = false;
                }
            }
            if (StringUtil.isEmpty(templateId)) {
                log.error("模板Id为空");
                flag = false;
            }
            if (flag) {
                // 获取消息模板详情
                MessageTemplateConfigEntity entity = messageTemplateConfigService.getInfo(templateId);
                // 替换参数
                String content = entity.getContent();
                // 替换参数
                if (StringUtil.isNotEmpty(content)) {
                    StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                    content = strSubstitutor.replace(content);
                }
                if(entity != null) {
                    MessageTypeEnum typeEnum = MessageTypeEnum.getByCode(entity.getMessageType());
                    String sendType = entity.getMessageType();
                    switch (typeEnum) {
                        case SysMessage:
                            // 站内消息
                            String title = entity.getTitle();
                            if (StringUtil.isNotEmpty(title)) {
                                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                                title = strSubstitutor.replace(title);
                            }
                            MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
                            messageService.sentMessage(toUserIdsList, title, content, userInfo);
                            if("1".equals(msgTemEntity.getMessageSource())){
                                content = null;
                            }
                                MessageMonitorEntity monitorEntity = createSysMessageMonitor(msgTemEntity,content,userInfo,toUserIdsList,title);
                                messageMonitorService.create(monitorEntity);
                            break;
                        case SmsMessage:
                            // 发送短信
                            JSONObject jsonObject1 = sendSms(toUserIdsList, model, parameterMap);
                            if (!(Boolean) jsonObject1.get("code")) {
                                return "发送短信消息失败，错误：" + jsonObject1.get("error");
                            }
                            break;
                        case MailMessage:
                            // 邮件
                            JSONObject jsonObject2 = SendMail(toUserIdsList, userInfo, sendType, model, parameterMap);
                            if (!(Boolean) jsonObject2.get("code")) {
                                return "发送邮件消息失败，错误：" + jsonObject2.get("error");
                            }
                            break;
                        case QyMessage:
                            // 企业微信
                            JSONObject jsonObject3 = SendQyWebChat(toUserIdsList, userInfo, sendType, model, parameterMap);
                            if (!(Boolean) jsonObject3.get("code")) {
                                return "发送企业微信消息失败，错误：" + jsonObject3.get("error");
                            }
                            break;
                        case DingMessage:
                            // 钉钉
                            JSONObject jsonObject4 = SendDingTalk(toUserIdsList, userInfo, sendType, model, parameterMap);
                            if (!(Boolean) jsonObject4.get("code")) {
                                return "发送钉钉消息失败，错误：" + jsonObject4.get("error");
                            }
                            break;
                        case WebHookMessage:
                            // webhook
                            JSONObject jsonObject5 = SendWebHook(sendType,userInfo, model, parameterMap);
                            if (!(Boolean) jsonObject5.get("code")) {
                                return "发送webhook消息失败，错误：" + jsonObject5.get("error");
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            return null;
    }

    private JSONObject SendWebHook(String sendType,UserInfo userInfo, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity entity = messageTemplateConfigService.getInfo(model.getTemplateId());
        String content = entity.getContent();
        JSONObject retJson = new JSONObject();
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());

        // 替换参数
        if (StringUtil.isNotEmpty(content)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            content = strSubstitutor.replace(content);
        }
        AccountConfigEntity entity1 = accountConfigService.getInfo(model.getAccountConfigId());
        if(entity != null) {
            //消息监控-消息模板写入
            monitorEntity.setMessageType(entity.getMessageType());
            monitorEntity.setMessageTemplateId(entity.getId());
            String title = entity.getTitle();
            if (StringUtil.isNotEmpty(title)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                title = strSubstitutor.replace(title);
            }
            monitorEntity.setTitle(title);
            monitorEntity.setReceiveUser(entity1.getWebhookAddress());
            monitorEntity.setContent(content);
            monitorEntity.setMessageSource(entity.getMessageSource());
            if(entity1 != null) {
                //消息监控-账号配置写入
                monitorEntity.setAccountId(entity1.getId());
                monitorEntity.setAccountCode(entity1.getEnCode());
                monitorEntity.setAccountName(entity1.getFullName());
                switch (entity1.getWebhookType()) {
                    case "1":
                        //钉钉
                        if ("1".equals(entity1.getApproveType())) {
                            JSONObject result = WebHookUtil.sendDDMessage(entity1.getWebhookAddress(), content);
                            messageMonitorService.create(monitorEntity);
                            if(ObjectUtil.isNotEmpty(result)) {
                                if (!"0".equals(result.get("errcode").toString())) {
                                    retJson.put("code", false);
                                    retJson.put("error", result.get("errmsg"));
                                    return retJson;
                                }
                            }else {
                                retJson.put("code", false);
                                retJson.put("error", "webhook账号地址配置错误！");
                                return retJson;
                            }
                        } else if ("2".equals(entity1.getApproveType())) {
                            JSONObject result = WebHookUtil.sendDingDing(entity1.getWebhookAddress(), entity1.getBearer(), content);
                            messageMonitorService.create(monitorEntity);
                            if(ObjectUtil.isNotEmpty(result)) {
                                if (!"0".equals(result.get("errcode").toString())) {
                                    retJson.put("code", false);
                                    retJson.put("error", result.get("errmsg"));
                                    return retJson;
                                }
                            }else {
                                retJson.put("code", false);
                                retJson.put("error", "webhook账号地址配置错误！");
                                return retJson;
                            }
                        }
                        break;
                    case "2":
                        if ("1".equals(entity1.getApproveType())) {
                            JSONObject result = WebHookUtil.callWeChatBot(entity1.getWebhookAddress(), content);
                            messageMonitorService.create(monitorEntity);
                            if (!"0".equals(result.get("errcode").toString())) {
                                retJson.put("code", false);
                                retJson.put("error", result.get("errmsg"));
                                return retJson;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }else {
                retJson.put("code", false);
                retJson.put("error", "账号配置数据不存在");
                messageMonitorService.create(monitorEntity);
                return retJson;
            }
        }else {
            retJson.put("code", false);
            retJson.put("error", "消息模板数据不存在");
            messageMonitorService.create(monitorEntity);
            return retJson;
        }
        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * 发送企业微信消息
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param parameterMap
     * @return
     */
    private JSONObject SendQyWebChat(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity entity = messageTemplateConfigService.getInfo(model.getTemplateId());
        AccountConfigEntity entity1 = accountConfigService.getInfo(model.getAccountConfigId());
        //创建消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        JSONObject retJson = new JSONObject();
        if(entity != null) {
            String content = entity.getContent();
            // 替换参数
            if (StringUtil.isNotEmpty(content)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                content = strSubstitutor.replace(content);
            }
            //消息监控-消息模板写入
            monitorEntity.setMessageType(entity.getMessageType());
            monitorEntity.setMessageSource(entity.getMessageSource());
            monitorEntity.setMessageTemplateId(entity.getId());
            String title = entity.getTitle();
            if (StringUtil.isNotEmpty(title)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                title = strSubstitutor.replace(title);
            }
            monitorEntity.setTitle(title);
            monitorEntity.setContent(content);
            // 获取系统配置
            if (entity1 != null) {
                //消息监控-账号配置写入
                monitorEntity.setAccountId(entity1.getId());
                monitorEntity.setAccountCode(entity1.getEnCode());
                monitorEntity.setAccountName(entity1.getFullName());

                Map<String, String> objModel = new HashMap<>();
                objModel.put("qyhCorpId", entity1.getEnterpriseId());
                objModel.put("qyhAgentId", entity1.getAppId());
                objModel.put("qyhAgentSecret", entity1.getAppSecret());
                BaseSystemInfo config = JsonUtil.getJsonToBean(objModel, BaseSystemInfo.class);
                String corpId = config.getQyhCorpId();
                String agentId = config.getQyhAgentId();
                // 获取的应用的Secret值
                String corpSecret = config.getQyhAgentSecret();

                String wxUserId = "";
                StringBuilder toWxUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();

                // 相关参数验证
                if (StringUtil.isEmpty(corpId)) {
                    retJson.put("code", false);
                    retJson.put("error", "企业ID为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(corpSecret)) {
                    retJson.put("code", false);
                    retJson.put("error", "Secret为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(agentId)) {
                    retJson.put("code", false);
                    retJson.put("error", "AgentId为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(content)) {
                    retJson.put("code", false);
                    retJson.put("error", "内容为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (toUserIdsList == null || toUserIdsList.size() < 1) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));

                // 获取接收人员的企业微信号、创建消息用户实体
                for (String userId : toUserIdsList) {
                    wxUserId = "";
                    // 从同步表获取对应的企业微信ID
                    SynThirdInfoEntity synThirdInfoEntity = synThirdInfoService.getInfoBySysObjId("1", "2", userId);
                    if (synThirdInfoEntity != null) {
                        wxUserId = synThirdInfoEntity.getThirdObjId();
                    }
                    if (StringUtil.isEmpty(wxUserId)) {
                        nullUserInfo = nullUserInfo.append(",").append(userId);
                    } else {
                        toWxUserId = toWxUserId.append("|").append(wxUserId);
                    }
                    messageReceiveList.add(JnpfMessageUtil.setMessageReceiveEntity(messageEntity.getId(), userId));
                }

                // 处理企业微信号信息串并验证
                toUserIdAll = toWxUserId.toString();
                if (StringUtil.isNotEmpty(toUserIdAll)) {
                    toUserIdAll = toUserIdAll.substring(1);
                }
                if (StringUtil.isEmpty(toUserIdAll)) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人对应的企业微信号全部为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 批量发送企业信息信息
                retJson = QyWebChatUtil.sendWxMessage(corpId, corpSecret, agentId, toUserIdAll, content);
                messageMonitorService.create(monitorEntity);
                if (!retJson.getBoolean("code")) {
                    return retJson;
                }

                // 企业微信号为空的信息写入备注
                if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                    messageEntity.setDescription(nullUserInfo.substring(1) + "对应的企业微信号为空");
                }
                // 写入系统的消息表、消息用户表

            } else {
                retJson.put("code", false);
                retJson.put("error", "账号配置数据不存在");
                messageMonitorService.create(monitorEntity);
                return retJson;
            }
        }else {
            retJson.put("code", false);
            retJson.put("error", "消息模板数据不存在");
            messageMonitorService.create(monitorEntity);
            return retJson;
        }
        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * List<String> toUserIdsList, UserInfo userInfo, String sendType, MessageTemplateEntity entity, Map<String, String> parameterMap
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param parameterMap
     * @return
     */
    private JSONObject SendDingTalk(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity entity = messageTemplateConfigService.getInfo(model.getTemplateId());
        AccountConfigEntity entity1 = accountConfigService.getInfo(model.getAccountConfigId());
        //创建消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        JSONObject retJson = new JSONObject();
        if(entity != null) {
            String content = entity.getContent();

            // 替换参数
            if (StringUtil.isNotEmpty(content)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                content = strSubstitutor.replace(content);
            }
            //消息监控-消息模板写入
            monitorEntity.setMessageType(entity.getMessageType());
            monitorEntity.setMessageSource(entity.getMessageSource());
            monitorEntity.setMessageTemplateId(entity.getId());
            String title = entity.getTitle();
            if (StringUtil.isNotEmpty(title)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                title = strSubstitutor.replace(title);
            }
            monitorEntity.setTitle(title);
            monitorEntity.setContent(content);
            // 获取系统配置
            if (entity1 != null) {
                //消息监控-账号配置写入
                monitorEntity.setAccountId(entity1.getId());
                monitorEntity.setAccountCode(entity1.getEnCode());
                monitorEntity.setAccountName(entity1.getFullName());

                Map<String, String> objModel = new HashMap<>();
                objModel.put("dingSynAppKey", entity1.getAppId());
                objModel.put("dingSynAppSecret", entity1.getAppSecret());
                objModel.put("dingAgentId", entity1.getAgentId());
                DingTalkModel dingTalkModel = JsonUtil.getJsonToBean(objModel, DingTalkModel.class);
                String appKey = dingTalkModel.getDingSynAppKey();
                String appSecret = dingTalkModel.getDingSynAppSecret();
                String agentId = dingTalkModel.getDingAgentId();
                String dingUserId = "";
                StringBuilder toDingUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();

                // 相关参数验证
                if (StringUtil.isEmpty(appKey)) {
                    retJson.put("code", false);
                    retJson.put("error", "AppKey为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(appSecret)) {
                    retJson.put("code", false);
                    retJson.put("error", "AppSecret为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(agentId)) {
                    retJson.put("code", false);
                    retJson.put("error", "AgentId为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(content)) {
                    retJson.put("code", false);
                    retJson.put("error", "内容为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (toUserIdsList == null || toUserIdsList.size() < 1) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));

                // 获取接收人员的钉钉号、创建消息用户实体
                for (String userId : toUserIdsList) {
                    dingUserId = "";
                    // 从同步表获取对应用户的钉钉ID
                    SynThirdInfoEntity synThirdInfoEntity = synThirdInfoService.getInfoBySysObjId("2", "2", userId);
                    if (synThirdInfoEntity != null) {
                        dingUserId = synThirdInfoEntity.getThirdObjId();
                    }
                    if (StringUtil.isEmpty(dingUserId)) {
                        nullUserInfo = nullUserInfo.append(",").append(userId);
                    } else {
                        toDingUserId = toDingUserId.append(",").append(dingUserId);
                    }
                    messageReceiveList.add(JnpfMessageUtil.setMessageReceiveEntity(messageEntity.getId(), userId));
                }

                // 处理接收人员的钉钉号信息串并验证
                toUserIdAll = toDingUserId.toString();
                if (StringUtil.isNotEmpty(toUserIdAll)) {
                    toUserIdAll = toUserIdAll.substring(1);
                }
                if (StringUtil.isEmpty(toUserIdAll)) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人对应的钉钉号全部为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 批量发送钉钉信息
                retJson = DingTalkUtil.sendDingMessage(appKey, appSecret, agentId, toUserIdAll, content);
                messageMonitorService.create(monitorEntity);
                if (!retJson.getBoolean("code")) {
                    return retJson;
                }

                // 钉钉号为空的信息写入备注
                if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                    messageEntity.setDescription(nullUserInfo.toString().substring(1) + "对应的钉钉号为空");
                }
                // 写入系统的消息表、消息用户表
            } else {
                retJson.put("code", false);
                retJson.put("error", "账号配置数据不存在");
                messageMonitorService.create(monitorEntity);
                return retJson;
            }
        }else {
            retJson.put("code", false);
            retJson.put("error", "消息模板数据不存在");
            messageMonitorService.create(monitorEntity);
            return retJson;
        }
        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * 发送邮件
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param parameterMap
     * @return
     */
    private JSONObject SendMail(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity entity = messageTemplateConfigService.getInfo(model.getTemplateId());
        // 获取系统配置
        AccountConfigEntity entity1 = accountConfigService.getInfo(model.getAccountConfigId());
        //创建消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        JSONObject retJson = new JSONObject();
        if(entity != null) {
            //消息监控-消息模板写入
            monitorEntity.setMessageType(entity.getMessageType());
            monitorEntity.setMessageSource(entity.getMessageSource());
            monitorEntity.setMessageTemplateId(entity.getId());
            String title = entity.getTitle();
            if (StringUtil.isNotEmpty(title)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                title = strSubstitutor.replace(title);
            }
            monitorEntity.setTitle(title);
            //消息内容
            String content = entity.getContent();
            if (StringUtil.isNotEmpty(content)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                content = strSubstitutor.replace(content);
            }
            monitorEntity.setContent(content);
            if(entity1 != null) {
                //消息监控-账号配置写入
                monitorEntity.setAccountId(entity1.getId());
                monitorEntity.setAccountCode(entity1.getEnCode());
                monitorEntity.setAccountName(entity1.getFullName());

                Map<String, String> objModel = new HashMap<>();
                objModel.put("emailSmtpHost", entity1.getSmtpServer());
                objModel.put("emailSmtpPort", entity1.getSmtpPort().toString());
                objModel.put("emailSenderName", entity1.getAddressorName());
                objModel.put("emailAccount", entity1.getSmtpUser());
                objModel.put("emailPassword", entity1.getSmtpPassword());

                EmailModel emailModel = JsonUtil.getJsonToBean(objModel, EmailModel.class);
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();
                StringBuilder toUserMail = new StringBuilder();
                String userEmailAll = "";
                String userEmail = "";
                String userName = "";

                // 相关参数验证
                if (StringUtil.isEmpty(emailModel.getEmailSmtpHost())) {
                    retJson.put("code", false);
                    retJson.put("error", "SMTP服务为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                } else if (StringUtil.isEmpty(emailModel.getEmailSmtpPort())) {
                    retJson.put("code", false);
                    retJson.put("error", "SMTP端口为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                } else if (StringUtil.isEmpty(emailModel.getEmailAccount())) {
                    retJson.put("code", false);
                    retJson.put("error", "发件人邮箱为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                } else if (StringUtil.isEmpty(emailModel.getEmailPassword())) {
                    retJson.put("code", false);
                    retJson.put("error", "发件人密码为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                } else if (toUserIdsList == null || toUserIdsList.size() < 1) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                } else {
                    // 设置邮件标题
                    emailModel.setEmailTitle(title);
                    // 设置邮件内容
                    emailModel.setEmailContent(content);

                    // 创建消息实体
                    MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), emailModel.getEmailTitle(), emailModel.getEmailContent(), Integer.parseInt(sendType));

                    // 获取收件人的邮箱地址、创建消息用户实体
                    for (String userId : toUserIdsList) {
                        UserEntity userEntity = userService.getInfo(userId);
                        if (userEntity != null) {
                            userEmail = StringUtil.isEmpty(userEntity.getEmail()) ? "" : userEntity.getEmail();
                            userName = userEntity.getRealName();
                        }
                        if (userEmail != null && !"".equals(userEmail)) {
                            if(EmailUtil.isEmail(userEmail)) {
                                toUserMail = toUserMail.append(",").append(userName).append("<").append(userEmail).append(">");
                            }
                        } else {
                            nullUserInfo = nullUserInfo.append(",").append(userId);
                        }
                        messageReceiveList.add(JnpfMessageUtil.setMessageReceiveEntity(messageEntity.getId(), userId));
                    }

                    // 处理接收人员的邮箱信息串并验证
                    userEmailAll = toUserMail.toString();
                    if (StringUtil.isNotEmpty(userEmailAll)) {
                        userEmailAll = userEmailAll.substring(1);
                    }
                    if (StringUtil.isEmpty(userEmailAll)) {
                        retJson.put("code", false);
                        retJson.put("error", "全部接收人对应的邮箱格式错误！");
                        messageMonitorService.create(monitorEntity);
                        return retJson;
                    } else {
                        // 设置接收人员
                        emailModel.setEmailToUsers(userEmailAll);
                        // 发送邮件
                        retJson = EmailUtil.sendMail(emailModel);
                        messageMonitorService.create(monitorEntity);
                        if (!retJson.getBoolean("code")) {
                            return retJson;
                        } else {
                            // 邮箱地址为空的信息写入备注
                            if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                                messageEntity.setDescription(nullUserInfo.substring(1) + "对应的邮箱为空");
                            }
                            // 写入系统的消息表、消息用户表
                        }
                    }
                }
            }else {
                retJson.put("code", false);
                retJson.put("error", "账号配置数据不存在");
                messageMonitorService.create(monitorEntity);
                return retJson;
            }
        }else {
            retJson.put("code", false);
            retJson.put("error", "消息模板数据不存在");
            messageMonitorService.create(monitorEntity);
            return retJson;
        }
        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * 发送短信
     *
     * @param toUserIdsList
     * @param parameterMap
     * @return
     */
    private JSONObject sendSms(List<String> toUserIdsList, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        UserInfo userInfo = userProvider.get();
        //获取短信配置
        AccountConfigEntity entity1 = accountConfigService.getInfo(model.getAccountConfigId());
        // 获取消息模板详情
        MessageTemplateConfigEntity entity = messageTemplateConfigService.getInfo(model.getTemplateId());
        //创建消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        JSONObject retJson = new JSONObject();
        if(entity != null) {
            //消息监控-消息模板写入
            monitorEntity.setMessageType(entity.getMessageType());
            monitorEntity.setMessageSource(entity.getMessageSource());
            monitorEntity.setMessageTemplateId(entity.getId());
            String title = entity.getTitle();
            if (StringUtil.isNotEmpty(title)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                title = strSubstitutor.replace(title);
            }
            monitorEntity.setTitle(title);
            if (entity1 != null) {
                //账号配置——短信
                Map<String, String> objModel = new HashMap<>(16);
                objModel.put("aliAccessKey", entity1.getAppId());
                objModel.put("aliSecret", entity1.getAppSecret());
                objModel.put("tencentSecretId", entity1.getAppId());
                objModel.put("tencentSecretKey", entity1.getAppSecret());
                objModel.put("tencentAppId", entity1.getSdkAppId());
                objModel.put("tencentAppKey", entity1.getAppKey());
                SmsModel smsConfig = JsonUtil.getJsonToBean(objModel, SmsModel.class);
                int company = Integer.parseInt(entity1.getChannel());
                //消息监控-账号配置写入
                monitorEntity.setAccountId(entity1.getId());
                monitorEntity.setAccountCode(entity1.getEnCode());
                monitorEntity.setAccountName(entity1.getFullName());
                // 组装接受用户
                StringBuffer toUserIdList = new StringBuffer();
                for (String toUserId : toUserIdsList) {
                    UserEntity userEntity = userService.getInfo(toUserId);
                    if(isPhone(userEntity.getMobilePhone())) {
                        toUserIdList.append(userEntity.getMobilePhone() + ",");
                    }
                }
                if(StringUtil.isEmpty(toUserIdList)){
                    retJson.put("code", false);
                    retJson.put("error", "全部接收人对应的手机号码格式错误！");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                //短信参数
                Map<String, Object> smsMap = new HashMap<>();
                if (entity != null) {
                    smsMap = smsFieldService.getParamMap(entity.getId(), parameterMap);
                } else {
                    retJson.put("code", false);
                    retJson.put("error", "消息模板数据不存在");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 发送短信
                String endPoint = "";
                if("1".equals(entity1.getChannel())){
                        endPoint = entity1.getEndPoint();
                }else if("2".equals(entity1.getChannel())){
                        endPoint = entity1.getZoneName();
                }
                String result = SmsUtil.sentSms(company, smsConfig, endPoint, entity1.getZoneParam(), toUserIdList.toString(), entity1.getSmsSignature(), entity.getTemplateCode(), smsMap);
                String content = SmsUtil.querySmsTemplateContent(company, smsConfig, endPoint, entity1.getZoneParam(), entity.getTemplateCode());
                if(StringUtil.isNotBlank(content) && !"null".equals(content)) {
                    if ("1".equals(entity1.getChannel())) {
                        if (content.contains("${")) {
                            for (String key : smsMap.keySet()) {
                                if(StringUtil.isNotBlank(String.valueOf(smsMap.get(key))) && smsMap.get(key)!=null) {
                                    String v = String.valueOf(smsMap.get(key));
                                    content = content.replace("${" + key + "}", smsMap.get(key).toString());
                                }
                            }
                        }
                    } else if ("2".equals(entity1.getChannel())) {
                        if (content.contains("{")) {
                            for (String key : smsMap.keySet()) {
                                if(StringUtil.isNotBlank(String.valueOf(smsMap.get(key))) && smsMap.get(key)!=null) {
                                    content = content.replace("{" + key + "}", smsMap.get(key).toString());
                                }
                            }
                        }
                    }
                }
                monitorEntity.setContent(content);
                messageMonitorService.create(monitorEntity);
                if (!"Ok".equalsIgnoreCase(result)) {
                    retJson.put("code", false);
                    retJson.put("error", result);
                    return retJson;
                }
            }else {
                retJson.put("code", false);
                retJson.put("error", "账号配置数据不存在");
                messageMonitorService.create(monitorEntity);
                return retJson;
            }
        }else {
            retJson.put("code", false);
            retJson.put("error", "消息模板数据不存在");
            messageMonitorService.create(monitorEntity);
            return retJson;
        }
        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * 获取系统配置
     */
    private Map<String, String> getSystemConfig() {
        // 获取系统配置
        List<SysConfigEntity> configList = sysconfigService.getList("SysConfig");
        Map<String, String> objModel = new HashMap<>(16);
        for (SysConfigEntity entity : configList) {
            objModel.put(entity.getFkey(), entity.getValue());
        }
        return objModel;
    }

    private MessageMonitorEntity createSysMessageMonitor(MessageTemplateConfigEntity msgTemEntity,String content,UserInfo userInfo,List<String> toUserIdsList,String title){
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setMessageType(msgTemEntity.getMessageType());
        monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setMessageTemplateId(msgTemEntity.getId());
        monitorEntity.setTitle(title);
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setContent(content);
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        return monitorEntity;
    }

    public static boolean isPhone(String phone){
        if (StringUtil.isNotBlank(phone) && !"null".equals(phone)) {
            return Pattern.matches("^1[3-9]\\d{9}$", phone);
        }
        return false;
    }
}
